<template>
    <div class="top_s">
      <van-icon name="arrow-left" @click="left" />
      <span style="margin-left: 140px">搜索商品</span>
    </div>
    <div>
      <van-search v-model="value" shape="round" placeholder="搜索商品名称" @search="search" />
    </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router'
const value = ref('')
const router = useRouter()

const search = async () => {
  if (value.value.trim() === '') return;

  // 记录搜索历史
  addToSearchHistory(value.value);

  try {
    // 请求后端商品数据
    // console.log('value.value', value.value);
    
    const response = await axios.get(`http://localhost:3000/dyx/home?name=${value.value}`);
    // console.log(response);
    
    // 假设后端返回的数据是数组，处理返回数据
    if (response.data && response.data.data) {
      // 假设这里是搜索成功后的处理逻辑
      // 使用 router.push 跳转到搜索详情页，传递搜索名称
      router.push({ 
        path: '/search_result', 
        query: { name: value.value } // 将搜索名称传递为查询参数
      });
    } else {
      console.error('没有找到相关商品');
    }
  } catch (error) {
    console.error('获取商品数据失败:', error);
  }
}
const searchHistory = ref<string[]>(JSON.parse(localStorage.getItem('searchHistory') || '[]'))

// 添加搜索记录到历史
const addToSearchHistory = (item: string) => {
  if (!searchHistory.value.includes(item)) {
    searchHistory.value.push(item)
    localStorage.setItem('searchHistory', JSON.stringify(searchHistory.value))
  }
}

// 返回上一级
const left = () => {
  router.go(-1)
}
</script>

<style scoped>
.top_s {
  width: 100%;
  height: 50px;
  line-height: 50px;
  font-size: 17px;
  padding-left: 10px;
}
</style>



<!-- <template>
  <div>
    <input 
      v-model="inputValue" 
      @input="debouncedInput" 
      placeholder="Type something..."
    />
    <button @click="throttledClick">Click Me</button>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';

// 创建响应式数据
const inputValue = ref('');

// 防抖函数
const debounce = (fn: Function, delay: number) => {
  let timeout: ReturnType<typeof setTimeout>;
  return function (...args: any[]) {
    clearTimeout(timeout);
    timeout = setTimeout(() => fn.apply(this, args), delay);
  };
};

// 节流函数
const throttle = (fn: Function, delay: number) => {
  let lastTime = 0;
  return function (...args: any[]) {
    const now = Date.now();
    if (now - lastTime >= delay) {
      lastTime = now;
      fn.apply(this, args);
    }
  };
};

// 防抖处理输入事件
const handleInput = () => {
  console.log('Input:', inputValue.value);
};

const debouncedInput = debounce(handleInput, 300); // 300ms 防抖延迟

// 节流处理按钮点击事件
const handleClick = () => {
  console.log('Button Clicked!');
};

const throttledClick = throttle(handleClick, 1000); // 1000ms 节流延迟
</script>

<style scoped>
input {
  margin-bottom: 10px;
}
</style> -->
